package com.lee.mysql.config;

import com.lee.mysql.dao.UserDao;
import com.lee.mysql.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//这里不用再加service了
public class ShiroUserRealm extends AuthorizingRealm {
    @Autowired
    private UserDao userDao;

    /**
     * 设置凭证匹配器（与用户添加操作使用相同的加密算法）
     * 可以使用setCredentialsMatcher
     * 也可以使用getCredentialsMatcher，二选其一
     * 使用get时返回的是hcMatcher
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher hcMatcher = new HashedCredentialsMatcher();
        hcMatcher.setHashAlgorithmName("MD5");
        hcMatcher.setHashIterations(1);
        super.setCredentialsMatcher(hcMatcher);
    }

    /** 获取用户认证信息，并提交给安全管理器 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String username = upToken.getUsername();
        User user = userDao.queryOneByLoginName(username);
        if(user==null)
            throw new UnknownAccountException();
        if(user.getLocked() == 1)
            throw new LockedAccountException();
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt, getName());

        return info;
    }

    /** 获取登陆用户的权限信息，并提交给安全管理器*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登陆用户
        User user = (User)principals.getPrimaryPrincipal();
        //查询用户所有权限标识
        List<String> permissions = userDao.getUserPermissions(user.getId());
        //用SET集合给权限去重
        Set<String> pms= new HashSet<>();
        for (String str : permissions) {
            if(!"".equals(str.trim()))pms.add(str);
        }
        //也可以使用lambda表达式
        //Arrays.asList(permissions).forEach(item->pms.add(item));
        SimpleAuthorizationInfo pmInfo = new SimpleAuthorizationInfo();
        pmInfo.setStringPermissions(pms);
        return pmInfo;
    }

}
